//
//  WSSearchBar.m
//  WSComponent
//
//  Created by lienbao on 25/08/2014.
//  Copyright (c) 2014 Lienbao. All rights reserved.
//

#import "WSSearchBar.h"
#import "UIComponent.h"

@interface WSSearchBar () <UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource>
{
    BOOL _lastIsShow;
}

@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) UIViewController *superViewController;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIButton *footerView;

@end

@implementation WSSearchBar

#pragma mark - getter and setter 
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:_resultFrame];
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
        gestureRecognizer.cancelsTouchesInView = NO;
        [_tableView addGestureRecognizer:gestureRecognizer];
    }
    return _tableView;
}

- (UIButton *)footerView
{
    if (!_footerView) {
        _footerView = [UIButton buttonWithType:UIButtonTypeCustom];
        [_footerView addTarget:self action:@selector(clearButtonAction)
              forControlEvents:UIControlEventTouchUpInside];
        [_footerView setTitle:@"清空搜索历史" forState:UIControlStateNormal];
        [_footerView setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        [_footerView setFrame:CGRectMake(0, 0, self.width, 36)];
    }
    return _footerView;
}

- (NSMutableArray *)searchResults
{
    if (!_searchResults) {
        _searchResults = [NSMutableArray array];
    }
    return _searchResults;
}

- (id)initWithFrame:(CGRect)frame withViewController:(UIViewController *)viewController;
{
    self = [super initWithFrame:frame];
    if (self) {
        
        // Initialization code
        _lastIsShow = NO;
        _superViewController = viewController;
        _tableViewCellClassName = @"WSTableViewCell";
        _edgeInsets = UIEdgeInsetsMake(0, 5, 0, 5);
        
        _leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_leftButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [_leftButton setTitleColor:[UIColor colorWithHex:0x586576 alpha:1.0] forState:UIControlStateNormal];
        [_leftButton setFrame:CGRectMake(0, 0, 0, self.height)];
        [self addSubview:_leftButton];
        
        _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 0, self.height)];
        _searchBar.placeholder = @"输入您想要搜索的~";
        [_searchBar setDelegate:self];
        [_searchBar setShowsCancelButton:NO];
        [_searchBar setCustomBackgroundImage:[UIImage clearColorImage]];
        [_searchBar setSearchFieldBackgroundImage:[[UIImage imageNamed:@"bg_search"] resizableImageWithCapInsets:UIEdgeInsetsMake(15, 4, 15, 4)]
                                         forState:UIControlStateNormal];
        [self addSubview:_searchBar];
        
        _cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_cancelButton setTitle:@"取消" forState:UIControlStateNormal];
        [_cancelButton addTarget:self action:@selector(cancelButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [_cancelButton setTitleColor:[UIColor colorWithHex:0x586576 alpha:1.0] forState:UIControlStateNormal];
        [_cancelButton setFrame:CGRectMake(0, 0, 48, self.height)];
        [self addSubview:_cancelButton];
        
        _rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_rightButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [_rightButton setTitleColor:[UIColor colorWithHex:0x586576 alpha:1.0] forState:UIControlStateNormal];
        [_rightButton setFrame:CGRectMake(0, 0, 0, self.height)];
        [self addSubview:_rightButton];
        
        _resultFrame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64);
        
        [self layoutSearchBarSubviews];

    }
    return self;
}

- (void)layoutSearchBarSubviews
{
    for(UIView *view in [self subviews]){
        [view removeFromSuperview];
    }
    
    [self addSubview:self.leftButton];
    [self addSubview:self.searchBar];
    [self showRightButton:!self.rightButton.hidden focus:NO];
}

- (void)showRightButton:(BOOL)isShow focus:(BOOL)isFocus
{
    [self.cancelButton removeFromSuperview];
    [self.rightButton removeFromSuperview];
    
    UIButton *showButton = isFocus ? self.cancelButton : self.rightButton;
    self.searchBar.left = (_edgeInsets.left + self.leftButton.width);
    self.searchBar.width = self.width - self.searchBar.left - (isShow ? (showButton.width > 0 ? showButton.width:_edgeInsets.right):_edgeInsets.right);
    if (isShow) {
        showButton.left = self.searchBar.right;
        [self addSubview:showButton];
    }
    DLog(@"search bar frame %@", NSStringFromCGRect(self.searchBar.frame));
}

- (void)showTableView:(BOOL)isShow
{
    if (isShow == _lastIsShow) {
        return;
    }
    _lastIsShow = isShow;
    
    self.tableView.alpha = isShow ? 0.6:1.0;
    if (isShow) {
        [self.superViewController.view addSubview:self.tableView];
    }
    
    [UIView animateWithDuration:0.618f animations:^{
        
        self.tableView.alpha = isShow ? 1.0:0.6;
        if (!isShow) {
            [self.tableView removeFromSuperview];
        }
        
    } completion:^(BOOL finished) {
        
    }];
}

- (void)hideKeyboard
{
    [self.searchBar resignFirstResponder];
}

- (void)clear
{
    [self resetStatus];
    self.searchBar.text  = @"";
}

- (void)resetStatus
{
    [self hideKeyboard];
    [self showRightButton:!self.rightButton.hidden focus:NO];;
    [self showTableView:NO];
}

- (void)reloadData
{
    self.tableView.tableFooterView = self.footerView;
    if ([self.searchBar.text length]) {
        [self.footerView setTitle:[self.searchResults count] ? @"暂无更多结果":@"暂无搜索结果" forState:UIControlStateNormal];
        if ([self.searchResults count]) {
            self.tableView.tableFooterView = nil;
        }
        self.footerView.enabled = NO;
    }else {
        [self.footerView setTitle:[self.searchResults count] ? @"清空搜索历史":@"暂无搜索历史" forState:UIControlStateNormal];
        self.footerView.enabled = [self.searchResults count] ? YES:NO;
    }
    [self.tableView reloadData];
}

- (void)loadSearchHistory
{
    [self.searchResults removeAllObjects];
    [self reloadData];
}

#pragma mark - ButtonClicked
- (void)buttonClicked:(id)sender
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(didClicked:button:)]) {
        [self.delegate didClicked:self button:sender];
    }
}

- (void)cancelButtonClicked:(id)sender
{
    [self resetStatus];
}

- (void)clearButtonAction
{
    [self reloadData];
}

#pragma mark - UISearchBarDelegate
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    return YES;
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    [self searchBar:searchBar textDidChange:@""];
    [self showRightButton:YES focus:YES];
    [self showTableView:YES];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if (![searchBar.text length]) {
        [self loadSearchHistory];
    }else {
        if (self.delegate && [self.delegate respondsToSelector:@selector(didSearch:keyWord:)]) {
            [self.delegate didSearch:self keyWord:searchBar.text];
        }
    }
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    if ([searchBar.text length]) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(didSearch:keyWord:)]) {
            [self.delegate didSearch:self keyWord:searchBar.text];
        }
    }
}

#pragma mark - UITableViewDelegate / UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.searchResults.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *identitify = [NSClassFromString(self.tableViewCellClassName) description];
    WSTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identitify];
    if (!cell) {
        cell = [[NSClassFromString(self.tableViewCellClassName) alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identitify];
    }
    
    if (indexPath.row < self.searchResults.count) {
        [cell tableViewCellWithData:[self.searchResults objectAtIndex:indexPath.row] forIndexPath:indexPath];
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row >= self.searchResults.count) {
        return [[((WSTableViewCell *)NSClassFromString(self.tableViewCellClassName)) class] cellHeight];
    }
    return [[((WSTableViewCell *)NSClassFromString(self.tableViewCellClassName)) class] accordHeight:[self.searchResults objectAtIndex:indexPath.row] forIndexPath:indexPath];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.searchResults.count > indexPath.row) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(didSelected:keyWord:)]) {
            [self.delegate didSelected:self keyWord:[self.searchResults objectAtIndex:indexPath.row]];
        }
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self hideKeyboard];
}

@end
